package javase.base;

/**
 * Java实现开方
 * User: Realfighter
 * Date: 2014/9/23
 * Time: 21:41
 */
public class MathSqrt {

    public static void main(String[] args) {
        float number = 9.0f;
        System.out.println(sqrt(number, 0.001f));
    }

    /**
     * 对传入参数开方，指定精度
     *
     * @param number
     * @param precision
     * @return
     */
    public static float sqrt(float number, float precision) {
        float start = 0.0f;
        float end = number;
        float index = 0.0f;
        float middle = (start + end) / 2;
        do {
            if (middle * middle > number) {
                end = middle;
            } else {
                start = middle;
            }
            index = middle;
            middle = (start + end) / 2;
        } while (Math.abs(middle - index) > precision);
        return middle;
    }

}
